// pages/publishPage/publishPage.js
import { promisify } from '../../../utils/promise.util'
import { $init, $digest } from '../../../utils/common.util'


var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {

    itemName: "",
    itemNameTag: true,
    itemInfo: "",
    itemInfoTag: true,
    price: 0,
    priceTag: true,
    pricingText: "定价",
    itemType: "",
    itemHint: "请输入闲置物品名称",
    itemID: 0,

    describeHint: "请简单描述一下物品的细节，新旧程度，型号尺码等",
    addText: "添加",
    classifyText: "分类",
    warnTip: "注意：发布虚假信息将被封号",
    submitText: "下一步：上架闲品",
    images: [],

    imagesTag: true,
    pricingHint: "请输入价格",
    yuan: "元",
    type1: "",
    type2: "",


    multiArray: [["生活娱乐", "母婴用品", "学习办公", "运动户外", "二次元", "数码极客", "文化艺术", "动植物", "其他", "穿搭美妆", "DIY"], ["生活百货", "食品生鲜", "家具家纺", "生活家电", "卡券服务"]],
    objectMultiArray: [
      [
        {
          id: 0,
          name: ' '
        },
        {
          id: 1,
          name: '生活用品'
        }
      ], [
        {
          id: 0,
          name: '生活娱乐'
        },
        {
          id: 1,
          name: '母婴用品'
        },
        {
          id: 2,
          name: '学习办公'
        },
        {
          id: 3,
          name: '运动户外'
        },
        {
          id: 4,
          name: '二次元'
        }
      ]
    ],
    multiIndex: [0, 0],
  },

  itemName: function (e) {
    var val = e.detail.value;
    this.setData({
      itemName: val
    });
  },

  itemDescribe: function (e) {
    var val = e.detail.value;
    this.setData({
      itemInfo: val
    })
  },

  chooseImage(e) {
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        const images = this.data.images.concat(res.tempFilePaths)
        this.data.images = images.length <= 3 ? images : images.slice(0, 3)
        console.log(this.data.images)

        console.log('一共' + this.data.images.length + '张图片')

        $digest(this)
      }
    })
  },

  removeImage(e) {
    const idx = e.target.dataset.idx
    this.data.images.splice(idx, 1)
    $digest(this)
  },

  handleImagePreview: function (e) {
    const idx = e.target.dataset.idx
    const images = this.data.images

    wx.previewImage({
      current: images[idx],
      urls: images,
    })
  },

  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },

  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = ["生活百货", "食品生鲜", "家具家纺", "生活家电", "卡券服务"];
            break;
          case 1:
            data.multiArray[1] = ["宝宝用品", "孕产用品", "童车玩具", "婴童鞋服"];
            break;
          case 2:
            data.multiArray[1] = ["办公设备", "办公耗材", "书籍文具"];
            break;
          case 3:
            data.multiArray[1] = ["健身用品", "户外用品", "运动穿戴", "骑行车品", "其他"];
            break;
          case 4:
            data.multiArray[1] = ["动漫周边", "游戏周边", "cosplay", "Lolita"];
            break;
          case 5:
            data.multiArray[1] = ["手机/平板", "手机配件", "电脑/配件", "影音用品", "游戏电玩", "其他配件"];
            break;
          case 6:
            data.multiArray[1] = ["文玩收藏", "工艺礼品", "玩具乐器"];
            break;
          case 7:
            data.multiArray[1] = ["宠物用品", "宠物", "园艺植物", "园艺用品"];
            break;
          case 8:
            data.multiArray[1] = ["其他"];
            break;
          case 9:
            data.multiArray[1] = ["女士鞋服", "男士鞋服", "时尚包包", "时尚配饰", "美容美妆"];
            break;
          case 10:
            data.multiArray[1] = ["手工DIY", "其他"];
            break;
        }
        data.multiIndex[1] = 0;
        console.log(data.multiIndex);
        break;
    }
    this.setData(data);
  },

  priceInput: function (e) {
    var val = e.detail.value;
    this.setData({
      price: val
    })
  },

  isPriceNumber: function (_keyword) {
    if (_keyword == "0" || _keyword == "0." || _keyword == "0.0" || _keyword == "0.00") {
      _keyword = "0"; return true;
    } else {
      var index = _keyword.indexOf("0");
      var length = _keyword.length;
      if (index == 0 && length > 1) {/*0开头的数字串*/
        var reg = /^[0]{1}[.]{1}[0-9]{1,2}$/;
        if (!reg.test(_keyword)) {
          return false;
        } else {
          return true;
        }
      } else {/*非0开头的数字*/
        var reg = /^[1-9]{1}[0-9]{0,10}[.]{0,1}[0-9]{0,2}$/;
        if (!reg.test(_keyword)) {
          return false;
        } else {
          return true;
        }
      }
      return false;
    }
  },

  checkType: function(e) {  
    if (!this.isPriceNumber(e.detail.value)) {
      wx.showToast({
        title: '价格输入错误！',
        icon: "none",
      });
    }
  },

  submitData: function () {
    var that = this;
    that.data.type1 = that.data.multiArray[0][that.data.multiIndex[0]];
    that.data.type2 = that.data.multiArray[1][that.data.multiIndex[1]];
    var id = 0;
    var uuid = "";
    var flag = "";
    var url = 'http://120.77.36.131:8180/STULive/uploadMoreGoods.action';
    var path = that.data.images;
    if(that.data.itemName.length == 0) {
      that.data.itemNameTag = false;
    } else {
      that.data.itemNameTag = true;
    }
    if(that.data.itemInfo.length == 0) {
      that.data.itemInfoTag = false;
    } else {
      that.data.itemInfoTag = true;
    }
    if(that.data.price == 0) {
      that.data.priceTag = false;
    } else {
      that.data.priceTag = true;
    }
    if(!that.data.itemNameTag || !that.data.itemInfoTag || !that.data.priceTag) {
      wx.showToast({
        title: '请完善物品信息！',
        icon: "none",
      });
      return false;
    }
    
    this.uploadImgs({
      url: url,
      path: path,
      id: id,
      uuid: uuid,
      flag: flag,

    });
    wx.showToast({
      title: '发布成功！',
    });
    
    setTimeout(function () {
      id = that.data.itemID;
      console.log('发送的ID为' + id)
      wx.navigateTo({
        url: '../goodsDetail/goodsDetail?goodsId='+id,
      })
    }, 1000);
    
    
  },

  uploadImgs: function (data) {
    var that = this;
    var i = data.i ? data.i : 0;
    var judge = (i == data.path.length - 1);
    var success = data.success ? data.success : 0;
    var fail = data.fail ? data.fail : 0;
    data.flag = judge ? "ok" : ""; 
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'file',
      formData: {
        price: that.data.price,
        info: that.data.itemInfo,
        rdSession: app.globalData.rdSession,
        title: that.data.itemName,
        type: that.data.type1 + "/" + that.data.type2,
        uuid: data.uuid,
        flag: data.flag,
      },
      success: (res) => {
        console.log('第' + i + '张上传成功');
        console.log(res.data);
        i++;
        if (i == data.path.length) {
          console.log('上传完毕');
          
          data.id = JSON.parse(res.data).data;
          that.data.itemID = data.id;
          console.log('id为：' + data.id);
          
        } else {
          //console.log(i);
          data.i = i;
          data.success = success;
          data.fail = fail;
          data.uuid = JSON.parse(res.data).data;
          that.uploadImgs(data);
          
        }
        success++;
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + 'fail:' + fail)
      },
      complete: (res) => {
        
      }
    })
    
  },

  submitMsg: function () {
    console.log(this.data.images);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    $init(this)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})